package cn.lyd.system.service.impl;

import cn.lyd.system.domain.Menu;
import cn.lyd.system.mapper.MenuMapper;
import cn.lyd.system.service.IMenuService;
import cn.lyd.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lyd
 * @since 2023-01-03
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 菜单树
     * @return
     */
    @Override
    public List<Menu> getMenuTree() {
        //查询所有的菜单
        List<Menu> allMenu = menuMapper.findAll();

        //把菜单id和菜单对象放到map里
        HashMap<Long, Menu> map = new HashMap<>();
        for (Menu menu : allMenu){
            map.put(menu.getId(),menu);
        }
        /*{
         22=Menu(name=组织机构管理, component=null, url=null, icon=el-icon-message, index=1, parent_id=null, intro=null, state=true),
         23=Menu(name=部门管理, component=org/Department, url=/department, icon=null, index=1, parent_id=22, intro=null, state=true),
         24=Menu(name=员工管理, component=org/Employee, url=/employee, icon=null, index=2, parent_id=22, intro=null, state=true)
         }*/

        //菜单树集合
        List<Menu> menuTree = new ArrayList<>();
        //遍历所有的菜单,parent_id为空=顶级菜单,放到菜单树集合里
        for (Menu menu : allMenu){
            if (menu.getParent_id()==null){
                menuTree.add(menu);
            }else {
                //parent_id非空=子菜单
                // 获取该菜单的父级菜单的id
                Long parent_id = menu.getParent_id();

                //正常清空下：一定是先有父级菜单才有子菜单,最好还是判断一下
                //获取父级菜单对象
                Menu fatherMenu = map.get(parent_id);
                if (fatherMenu!=null){
                    //把这个菜单作为子菜单放进去
                    List<Menu> childrenMenu = fatherMenu.getChildren();
                    childrenMenu.add(menu);
                }
            }
        }
        //循环完后，返回菜单树
        return menuTree;
    }

}
